# -*- coding: utf-8 -*-
# @Time    : 2020/8/30 16:55
# @Author  : liupengfei
# @File    : serializers.py
from utils.serializersfield import BooleanCharField
from .models import Option, Upload

from rest_framework import serializers


class OptionDictSerializer(serializers.ModelSerializer):
    icon = serializers.SerializerMethodField()
    code = serializers.IntegerField(source='id', read_only=True)
    codeName = serializers.CharField(source='name', read_only=True)

    def get_icon(self, obj):
        icon_arr = obj.icon.split('|')
        if len(icon_arr) > 1:
            return icon_arr
        return [obj.icon, ]

    # 系统分类下拉列表
    class Meta:
        model = Option
        fields = ('code', 'id', 'codeName', 'icon')


class OptionSerializer(serializers.ModelSerializer):
    type_text = serializers.CharField(source='get_type_display', read_only=True)
    enable_text = BooleanCharField(source='enable', read_only=True)
    enabled = serializers.SerializerMethodField()

    class Meta:
        model = Option
        fields = '__all__'

    def get_enabled(self, obj):  # 修改时填充CheckBox使用
        if obj.enable:
            return [1]
        else:
            return []


class UploadSerializer(serializers.ModelSerializer):
    file_path = serializers.SerializerMethodField()

    def get_file_path(self, obj):
        return obj.get_url()

    class Meta:
        model = Upload
        fields = '__all__'


class ImagesSerializer(serializers.ModelSerializer):
    file_path = serializers.SerializerMethodField()

    def get_file_path(self, obj):
        return obj.get_url()

    class Meta:
        model = Upload
        fields = ('id', 'file_path')
